﻿using Microsoft.AspNetCore.SignalR;
using XmppDotNet;
using XmppDotNet.Transport.Socket;
using XmppDotNet.Transport;
using System.Diagnostics;
using System.Reactive.Linq;
using XmppDotNet.Extensions.Client.Presence;
using XmppDotNet.Xmpp;
using XmppDotNet.Xmpp.Base;
using XmppDotNet.Xml;
using XmppDotNet.Extensions.Client.Message;

namespace XmppWebTest
{
    /// <summary>
    /// XMPP服务 - 负责与XMPP服务器交互，并将消息推送到SignalR
    /// </summary>
    public class XmppService
    {
        private readonly IHubContext<ChatHub> _hubContext;  // SignalR 依赖
        private readonly XmppClient _xmppClient;


        public XmppService(IHubContext<ChatHub> hubContext)  // 注入 IHubContext
        {
            _hubContext = hubContext;  // 赋值 SignalR 依赖
            _xmppClient = new XmppClient(
                conf =>
                {
                    conf.UseSocketTransport(new StaticNameResolver(new Uri("tcp://47.117.74.76:5222")))
                        .WithCertificateValidator(new AlwaysAcceptCertificateValidator());
                }
            )
            {
                Jid = "jxh@izeellvnf5htoqz", // XMPP 用户 JID
                Password = "hilink123456"
            };

            _xmppClient.StateChanged.Subscribe(state => { });

            // 监听 XMPP 收到的消息，并转发给 SignalR
            _xmppClient.XmppXElementReceived
                .Where(el => el is Message&&el.Cast<Message>().Body != null)
                .Subscribe(el =>
                {
                    var message = el.Cast<Message>();
                    var sender = message.From;
                    var text = message.Body;

                    Debug.WriteLine($"收到 XMPP 消息：{sender}: {text}");

                    // 通过 SignalR 广播消息到前端
                    _hubContext.Clients.All.SendAsync("ReceiveMessage", sender, text);
                });

            // 连接 XMPP 服务器
            _xmppClient.ConnectAsync().Wait();
            _xmppClient.SendPresenceAsync(Show.Chat, "在线").Wait();
        }

        //// 监听 XMPP 服务器消息并转发到 SignalR
        //public async Task OnXmppMessageReceived(string sender, string text)
        //{
        //    Console.WriteLine($"从 XMPP 收到消息: {sender}: {text}");

        //    // 使用 IHubContext 发送 SignalR 消息
        //    await _hubContext.Clients.All.SendAsync("ReceiveMessage", sender, text);
        //}

        // 发送 XMPP 消息
        public async Task SendMessageToXmpp(string recipient, string message)
        {
            await _xmppClient.SendChatMessageAsync(recipient, message);
        }

    }
}
